/*
 * @Author: fisher
 * @Date: 2024-02-26 11:09:16
 * @LastEditors: fisher luthor-li@qq.com
 * @LastEditTime: 2024-08-26 15:55:38
 * @FilePath: \pscluster\services\ueinstanceService.js
 * @Description:
 */
// services/ueInstanceService.js
const { execSync } = require('child_process')
const fs = require('fs-extra')
const path = require('path')
const platform = process.env.PLATFORM
const { findExeFilesSync, findShFilesSync } = require('../utils/common')
/**
 * @description: 创建实例
 * @param {*} data
 * @return {*}
 */

const startUeinstance = async data => {
  // PixelStreamingURL, instanceId, uePath
  try {
    // 获取cluster.json文件中已有信息
    // 指定配置文件路径
    const configPath = path.resolve(__dirname, '../cluster.json') // 根据您的实际配置文件位置来更改路径
    // 读取 JSON 配置文件内容
    const confogJson = await fs.readJson(configPath)
    // 修改配置文件
    // confogJson.ueserver

    for (let i = 0, len = data.length; i < len; i++) {
      // 在集群文件中查询是否已经启动过，如果启动过采取reload方式，如果没启动过则重新设置启动命令
      const target = confogJson.ueserver.find(
        item => item.name == `ue_${data[i].instanceId}`
      )
      let cmd = ''
      if (target) {
        cmd = `pm2 reload ${target.name}`
        execSync(cmd)
        target.status = true
      } else {
        // 获取ue工程中exe文件名称
        // 获取ue exe文件名称或sh文件
        let exeFile = ''
        if (platform == 'windows') {
          exeFile = await findExeFilesSync(data[i].path)
        } else if (platform == 'linux') {
          exeFile = await findShFilesSync(data[i].path)
        }
        // const exeFile = await findExeFilesSync(data[i].path)
        cmd = `pm2 start ${path.join(data[i].path, exeFile)} --name ue_${data[i].instanceId} -- -RenderOffscreen -Unattended -AudioMixer -PixelStreamingURL=${data[i].PixelStreamingURL}`
        execSync(cmd)
        confogJson.ueserver.push({
          name: `ue_${data[i].instanceId}`,
          status: true,
          path: data[i].path,
          createAt: Date.now()
        })
      }
    }

    // 写回 JSON 配置文件
    await fs.writeJson(configPath, confogJson, { spaces: 2 })
  } catch (err) {
    throw new HttpError(err.message, 400)
  }
}

const stopUeinstance = async ids => {
  try {
    // 获取cluster.json文件中已有信息
    // 指定配置文件路径
    const configPath = path.resolve(__dirname, '../cluster.json') // 根据您的实际配置文件位置来更改路径
    // 读取 JSON 配置文件内容
    const confogJson = await fs.readJson(configPath)
    let stopStr = ''
    for (let i = 0, len = ids.length; i < len; i++) {
      const serverName = `ue_${ids[i]}`
      stopStr += serverName + ' '
      const target = confogJson.ueserver.find(item => item.name === serverName)
      if (target) target.status = false
    }
    // 写回 JSON 配置文件
    await fs.writeJson(configPath, confogJson, { spaces: 2 })
    const cmd = `pm2 stop ${stopStr}`
    console.log('stopStr ===', cmd)
    execSync(cmd)
  } catch (err) {
    throw new HttpError(err.message, 400)
  }
}
const deleteUeinstance = async ids => {
  try {
    // 获取cluster.json文件中已有信息
    // 指定配置文件路径
    const configPath = path.resolve(__dirname, '../cluster.json') // 根据您的实际配置文件位置来更改路径
    // 读取 JSON 配置文件内容
    const confogJson = await fs.readJson(configPath)
    let deleteStr = ''
    for (let i = 0, len = ids.length; i < len; i++) {
      const serverName = `ue_${ids[i]}`
      deleteStr += serverName + ' '
      confogJson.ueserver = confogJson.ueserver.filter(
        item => item.name !== serverName
      )
    }
    // 写回 JSON 配置文件
    await fs.writeJson(configPath, confogJson, { spaces: 2 })
    const cmd = `pm2 delete ${deleteStr}`
    console.log('stopStr ===', cmd)
    execSync(cmd)
  } catch (err) {
    throw new HttpError(err.message, 400)
  }
}
module.exports = {
  startUeinstance,
  stopUeinstance,
  deleteUeinstance
}
